package com.egg.ylt.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.egg.ylt.MainActivity;
import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.GlideCircleTransform;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.pojo.UpLoadFileEntity;
import com.egg.ylt.pojo.UserByidEntity;
import com.egg.ylt.presenter.impl.CenterPresenterImpl;
import com.egg.ylt.uploadingphoto.UriUtils;
import com.egg.ylt.view.ICenterView;
import com.ruffian.library.widget.RImageView;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.AppSharedPreferences;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.yonyou.framework.library.dialog.AlertDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_UserInfo extends BaseActivity<CenterPresenterImpl> implements ICenterView {


    @BindView(R.id.include_iv_back)
    ImageView includeIvBack;
    @BindView(R.id.include_tv_title)
    TextView includeTvTitle;
    @BindView(R.id.include_tv_right)
    TextView includeTvRight;
    @BindView(R.id.include_rl_view)
    RelativeLayout includeRlView;
    @BindView(R.id.iv_user_head)
    RImageView ivUserHead;
    @BindView(R.id.tv_user_name)
    EditText tvUserName;
    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.ll_loading_view)
    LinearLayout llLoadingView;

    private AlertDialog mOpenCamersDialog;

    private boolean mType = true;

    // 拍照回传码
    public final static int CAMERA_REQUEST_CODE = 0;
    // 相册选择回传吗
    public final static int GALLERY_REQUEST_CODE = 1;
    //系统剪裁
    private final static int GO_TO_ZOOM = 3;

    //相关系统权限
    private String[] PERMISSIONS_STORAGE = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};
    // 拍照的照片的存储位置
    private String mTempPhotoPath;
    // 照片所在的Uri地址
    private Uri imageUri;

    //调用照相机返回图片文件
    private Uri imageCropUri;
    private AppSharedPreferences mSp;

    private String imgUrl;

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_user_info;
    }

    @Override
    protected View getLoadingTargetView() {
        return llLoadingView;
    }

    @Override
    protected void initViewsAndEvents() {

        StatusBarUtil.setStatusBarColor(this, R.color.ylt_whit);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(mContext, includeRlView);

        //设置title
        includeTvTitle.setText("个人信息");

        //裁剪图片后的保存地址
        imageCropUri = getUri();

        initView();
    }

    private void initView() {
        //设置用户名 和 手机号
        mSp = new AppSharedPreferences(mContext);
        //请求用户信息
        mPresenter.getUserInfo(Constants.TOKEN);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void getUserInfo(UserByidEntity entity) {
        if (entity == null) {
            return;
        }
        //用户头像
        imgUrl = entity.getHeadImage();
        Glide.with(mContext)
                .load(entity.getHeadImage())
                .error(R.mipmap.ic_mother)
                .fallback(R.mipmap.ic_mother)
                .transform(new GlideCircleTransform(mContext))
                .transition(new DrawableTransitionOptions().crossFade())
                .into(ivUserHead);
        //用户昵称
        if (!StringUtil.isEmpty(entity.getName())) {
            tvUserName.setText(entity.getName());
        }

        //用户手机号
        tvUserPhone.setText(CustomUtils.setPhoneHide(entity.getPhone()));

    }

    @Override
    public void onPostPhoto() {
        //上传图片路径成功后请求个人信息
        finish();
    }

    @Override
    public void getImgUri(UpLoadFileEntity entity) {
        //上传图片到公共服务器获取图片路径
        if (entity == null) {
            return;
        }
        imgUrl = entity.getShowImg();
        Glide.with(mContext)
                .load(imgUrl)
                .error(R.mipmap.ic_mother)
                .fallback(R.mipmap.ic_mother)
                .transform(new GlideCircleTransform(mContext))
                .transition(new DrawableTransitionOptions().crossFade())
                .into(ivUserHead);
//        mPresenter.postPhoto(Constants.TOKEN, "", entity.getShowImg());
    }

    @OnClick({R.id.include_iv_back, R.id.ll_head_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.include_iv_back://返回键
                String tvName = tvUserName.getText().toString().trim();
                mPresenter.postPhoto(Constants.TOKEN, tvName, imgUrl);
                break;
            case R.id.ll_head_img://上传头像
                requestPhotosPermissions();
                break;
        }
    }


    /**
     * 打开相机和相册的弹出框
     */
    public void OpenCameraDialog() {
        mOpenCamersDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_open_camera)
                .fromBottom(true)
                .fullWidth()
                .setOnClickListener(R.id.tv_photo_album, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        choosePhoto();
                    }
                })
                .setOnClickListener(R.id.tv_take_photos, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        takePhoto();
                    }
                })
                .setOnClickListener(R.id.tv_cancel_camera, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOpenCamersDialog.dismiss();
                    }
                })
                .show();
    }

    /**
     * 点击拍照,动态申请权限
     */
    public void requestPhotosPermissions() {
        //第二个参数是需要申请的权限
        if (ContextCompat.checkSelfPermission(mContext,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // 进入这儿表示没有权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(mContext, Manifest.permission.CAMERA)) {
                // 提示已经禁止
                ActivityCompat.requestPermissions(mContext, PERMISSIONS_STORAGE, CAMERA_REQUEST_CODE);
            } else {
                //权限还没有授予，需要在这里写申请权限的代码
                // 第二个参数是一个字符串数组，里面是你需要申请的权限 可以设置申请多个权限
                // 最后一个参数是标志你这次申请的权限，该常量在onRequestPermissionsResult中使用到
                ActivityCompat.requestPermissions(mContext, PERMISSIONS_STORAGE, CAMERA_REQUEST_CODE);
            }

        } else { //权限已经被授予，在这里直接写要执行的相应方法即可
            OpenCameraDialog();
        }
    }

    /**
     * 拍照实现方法
     */
    private void takePhoto() {
        //打开相机后，关闭弹出框
        mOpenCamersDialog.dismiss();

        // 跳转到系统的拍照界面
        Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定照片存储位置为sd卡本目录下
        // 这里设置为固定名字 这样就只会只有一张temp图 如果要所有中间图片都保存可以通过时间或者加其他东西设置图片的名称
        // File.separator为系统自带的分隔符 是一个固定的常量
        mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg";
        // 获取图片所在位置的Uri路径    *****这里为什么这么做参考问题2*****
        /*imageUri = Uri.fromFile(new File(mTempPhotoPath));*/
        imageUri = FileProvider.getUriForFile(mContext, "com.egg.provider",
                new File(mTempPhotoPath));
        //下面这句指定调用相机拍照后的照片存储的路径
        intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intentToTakePhoto, CAMERA_REQUEST_CODE);
    }

    /**
     * 打开相册方法实现
     */
    private void choosePhoto() {
        //选择相册后，关闭弹出框
        mOpenCamersDialog.dismiss();

        Intent intentToPickPic = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 如果限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型" 所有类型则写 "image/*"
        intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intentToPickPic, GALLERY_REQUEST_CODE);
    }

    /**
     * 界面回调方法 用于将得到的照片处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case CAMERA_REQUEST_CODE:   //调用相机后返回
                if (resultCode == MainActivity.RESULT_OK) {
                    cropPhoto(imageUri);       //裁剪
                }
                break;
            case GALLERY_REQUEST_CODE:    //调用相册后返回
                if (resultCode == MainActivity.RESULT_OK) {
                    Uri uri = data.getData();
                    cropPhoto(uri);       //裁剪
                }
                break;
            case GO_TO_ZOOM:     //调用剪裁后返回
                if (resultCode == MainActivity.RESULT_OK) {
                    mType = false;
                    String encodedPath = imageCropUri.getEncodedPath();
                    Uri uriFromFilePath = UriUtils.getUriFromFilePath(encodedPath);
                    upLoad(uriFromFilePath);
                }
                break;
        }

    }

    //把图片上传到服务器
    public void upLoad(Uri uri) {
        Bitmap bitmap = UriUtils.decodeUriAsBitmap(this, uri);
        String photo = saveImage("photo", bitmap);
        mPresenter.upImg(photo);
    }

    /**
     * 权限申请回调方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                OpenCameraDialog();
            } else {
                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }

    }


    /**
     * 裁剪图片
     */
    private void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
//        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        //裁剪之后，保存在裁剪文件中，关键
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageCropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, GO_TO_ZOOM);
    }

    /**
     * 得到存储图片bitmap的路径
     *
     * @param name
     * @param bmp
     * @return
     */
    public String saveImage(String name, Bitmap bmp) {
        File appDir = new File(Environment.getExternalStorageDirectory().getPath());
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = name + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Uri getUri() {
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/image/");
        if (!tmpDir.exists()) {
            tmpDir.mkdirs();
        }
        File img = new File(tmpDir.getAbsolutePath() + "/pic.jpeg");
        if (img.exists()) {
            img.delete();
        }
        return Uri.fromFile(img);
    }

}
